<template>
  <a-modal
    :maskClosable="maskClosable"
    title="添加云平台资源"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="资源名称">
          <a-input
            autocomplete="off"
            v-decorator="['name', decoratorOptions.name]"
          />
        </a-form-item>
        <a-form-item label="资源类型">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['type', decoratorOptions.type]"
            @change="handleChange"
          >
            <a-select-option
              v-for="(t, index) in typeList"
              :key="index"
              :value="t.value"
            >
              {{ t.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数据中心">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['datacenterId', decoratorOptions.datacenterId]"
            @change="loadClusterList"
          >
            <a-select-option
              v-for="(item, index) in datacenterList"
              :key="'datacenterId_' + index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <template v-if="cloudType === 1">
          <a-form-item label="集群模式">
            <a-radio-group v-model="setting">
              <a-radio :value="0"> 选择已有集群 </a-radio>
              <a-radio :value="1"> 新增集群 </a-radio>
            </a-radio-group>
          </a-form-item>
          <template v-if="setting < 1">
            <a-form-item extra="选择已有集群" label="集群">
              <a-select
                :getPopupContainer="
                  (triggerNode) => {
                    return triggerNode.parentNode || document.body;
                  }
                "
                v-decorator="['clusterId', decoratorOptions.clusterId]"
              >
                <a-select-option
                  v-for="d in clusterList"
                  :key="d.id"
                  :value="d.id"
                >
                  {{ d.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item extra="新增集群的名称" label="集群名称">
              <a-input
                autocomplete="off"
                v-decorator="['clusterName', decoratorOptions.clusterName]"
              />
            </a-form-item>
          </template>
          <a-form-item label="迁移服务IP">
            <a-input
              autocomplete="off"
              v-decorator="['restveleroIp', decoratorOptions.restveleroIp]"
            />
          </a-form-item>
        </template>
        <template v-if="cloudType === 3">
          <a-form-item label="地域">
            <a-select
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body;
                }
              "
              v-decorator="['huaweiRegionId', decoratorOptions.huaweiRegionId]"
            >
              <a-select-option
                v-for="d in huaweiRegionList"
                :key="d.RegionId"
                :value="d.RegionId"
              >
                {{ d.LocalName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="访问KEY">
            <a-input
              autocomplete="off"
              v-decorator="['accessKey', decoratorOptions.accessKey]"
            />
          </a-form-item>
          <a-form-item label="访问秘钥">
            <a-input
              autocomplete="off"
              v-decorator="['secretKey', decoratorOptions.secretKey]"
            />
          </a-form-item>
        </template>
        <template v-if="cloudType === 2">
          <a-form-item label="地域">
            <a-select
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body;
                }
              "
              v-decorator="['aliRegionId', decoratorOptions.aliRegionId]"
            >
              <a-select-option
                v-for="d in aliRegionList"
                :key="d.RegionId"
                :value="d.RegionId"
              >
                {{ d.LocalName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item label="系统盘大小">
            <a-input
              autocomplete="off"
              addon-after="GB"
              @keyup="clearNoNum('systemDiskSize')"
              @blur="clearNoNum('systemDiskSize')"
              v-decorator="['systemDiskSize', decoratorOptions.systemDiskSize]"
            />
          </a-form-item> -->
          <a-form-item label="访问KEY">
            <a-input
              autocomplete="off"
              v-decorator="['accessKeyId', decoratorOptions.accessKeyId]"
            />
          </a-form-item>
          <a-form-item label="访问秘钥">
            <a-input
              autocomplete="off"
              v-decorator="['accessSecret', decoratorOptions.accessSecret]"
            />
          </a-form-item>
        </template>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { gPostAction, postAction, getAction } from "@/api/manage";
import { filterNoNum } from "@/utils/util";
export default {
  name: "AddModal",
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      clusterList: [],
      datacenterList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        clusterList: "/cluster/queryList",
      },
      initObj: {},
      setting: 0,
      cloudType: 1,
      maskClosable: false,
      typeList: [
        {
          name: "Kubernetes容器云",
          value: 1,
        },
        {
          name: "阿里云",
          value: 2,
        },
        {
          name: "华为云",
          value: 3,
        },
      ],
      aliRegionList: [
        {
          RegionId: "cn-qingdao",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "华北1（青岛）",
        },
        {
          RegionId: "cn-beijing",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "华北2（北京）",
        },
        {
          RegionId: "cn-zhangjiakou",
          RegionEndpoint: "ecs.cn-zhangjiakou.aliyuncs.com",
          LocalName: "华北3（张家口）",
        },
        {
          RegionId: "cn-huhehaote",
          RegionEndpoint: "ecs.cn-huhehaote.aliyuncs.com",
          LocalName: "华北5（呼和浩特）",
        },
        {
          RegionId: "cn-wulanchabu",
          RegionEndpoint: "ecs.cn-wulanchabu.aliyuncs.com",
          LocalName: "华北6（乌兰察布）",
        },
        {
          RegionId: "cn-hangzhou",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "华东1（杭州）",
        },
        {
          RegionId: "cn-shanghai",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "华东2（上海）",
        },
        {
          RegionId: "cn-shenzhen",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "华南1（深圳）",
        },
        {
          RegionId: "cn-heyuan",
          RegionEndpoint: "ecs.cn-heyuan.aliyuncs.com",
          LocalName: "华南2（河源）",
        },
        {
          RegionId: "cn-guangzhou",
          RegionEndpoint: "ecs.cn-guangzhou.aliyuncs.com",
          LocalName: "华南3（广州）",
        },
        {
          RegionId: "cn-chengdu",
          RegionEndpoint: "ecs.cn-chengdu.aliyuncs.com",
          LocalName: "西南1（成都）",
        },
        {
          RegionId: "cn-hongkong",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "中国（香港）",
        },
        {
          RegionId: "ap-northeast-1",
          RegionEndpoint: "ecs.ap-northeast-1.aliyuncs.com",
          LocalName: "亚太东北 1 (东京)",
        },
        {
          RegionId: "ap-southeast-1",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "亚太东南 1 (新加坡)",
        },
        {
          RegionId: "ap-southeast-2",
          RegionEndpoint: "ecs.ap-southeast-2.aliyuncs.com",
          LocalName: "亚太东南 2 (悉尼)",
        },
        {
          RegionId: "ap-southeast-3",
          RegionEndpoint: "ecs.ap-southeast-3.aliyuncs.com",
          LocalName: "亚太东南 3 (吉隆坡)",
        },
        {
          RegionId: "ap-southeast-5",
          RegionEndpoint: "ecs.ap-southeast-5.aliyuncs.com",
          LocalName: "亚太东南 5 (雅加达)",
        },
        {
          RegionId: "ap-south-1",
          RegionEndpoint: "ecs.ap-south-1.aliyuncs.com",
          LocalName: "亚太南部 1 (孟买)",
        },
        {
          RegionId: "us-east-1",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "美国东部 1 (弗吉尼亚)",
        },
        {
          RegionId: "us-west-1",
          RegionEndpoint: "ecs.aliyuncs.com",
          LocalName: "美国西部 1 (硅谷)",
        },
        {
          RegionId: "eu-west-1",
          RegionEndpoint: "ecs.eu-west-1.aliyuncs.com",
          LocalName: "英国 (伦敦)",
        },
        {
          RegionId: "me-east-1",
          RegionEndpoint: "ecs.me-east-1.aliyuncs.com",
          LocalName: "中东东部 1 (迪拜)",
        },
        {
          RegionId: "eu-central-1",
          RegionEndpoint: "ecs.eu-central-1.aliyuncs.com",
          LocalName: "欧洲中部 1 (法兰克福)",
        },
      ],
      huaweiRegionList: [
        {
          RegionId: "cn-north-1",
          LocalName: "华北-北京一",
        },
        {
          RegionId: "cn-north-4",
          LocalName: "华北-北京四",
        },
        {
          RegionId: "cn-east-3",
          LocalName: "华东-上海一",
        },
        {
          RegionId: "cn-east-2",
          LocalName: "华东-上海二",
        },
        {
          RegionId: "cn-south-1",
          LocalName: "华南-广州",
        },
        {
          RegionId: "ap-southeast-1",
          LocalName: "亚太-香港",
        },
      ],
      decoratorOptions: {
        name: {
          rules: [
            { required: true, message: "请输入国网云名称" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
          ],
        },
        datacenterId: {
          rules: [{ required: true, message: "请选择数据中心" }],
        },
        clusterName: {
          rules: [
            { required: true, message: "请输入集群名称" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
          ],
        },
        type: {
          rules: [{ required: true, message: "请选择国网云类型" }],
        },
        clusterId: {
          rules: [{ required: true, message: "请选择集群" }],
        },
        restveleroIp: {
          rules: [
            { required: true, message: "请输入迁移服务IP" },
            { validator: this.validators.noWhitespace() },
            // { validator: this.validators.isValidIp() },
          ],
        },
        huaweiRegionId: {
          rules: [{ required: true, message: "请选择数据中心" }],
        },
        accessKey: {
          rules: [
            { required: true, message: "请输入访问KEY" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" },
          ],
        },
        secretKey: {
          rules: [
            { required: true, message: "请输入访问秘钥" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" },
          ],
        },
        aliRegionId: {
          rules: [{ required: true, message: "请选择地域" }],
        },
        systemDiskSize: {
          rules: [
            { required: true, message: "请输入系统盘大小" },
            { validator: this.validators.xmax({ max: 9999 }), trigger: "blur" },
            { validator: this.validators.xmin({ min: 0 }), trigger: "blur" },
          ],
        },
        accessKeyId: {
          rules: [
            { required: true, message: "请输入访问KEY" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" },
          ],
        },
        accessSecret: {
          rules: [
            { required: true, message: "请输入访问秘钥" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" },
          ],
        },
      },
    };
  },
  methods: {
    clearNoNum(fieldName) {
      let obj = {};
      obj[fieldName] = filterNoNum(this.form.getFieldValue(fieldName));
      this.form.setFieldsValue(obj);
      this.form.validateFields([fieldName], (errors, values) => {});
    },
    loadDatacenterList() {
      this.datacenterList = [];
      gPostAction("/asset/pageDatacenter", { pageSize: 999 }).then((res) => {
        if (res.success) {
          const data = res.data;
          if (data && data.list && data.list.length) {
            this.datacenterList = data.list;
            this.form.setFieldsValue({
              datacenterId: data.list[0].id,
            });
            this.loadClusterList(data.list[0].id);
          }
        }
      });
    },
    loadClusterList(recordId) {
      getAction(this.url.clusterList, { datacenterId: recordId }).then(
        (res) => {
          if (res.data) {
            this.clusterList = res.data.clusters;
          }
        }
      );
    },
    add() {
      this.visible = true;
      this.$nextTick(() => {
        this.form.resetFields();
        this.loadDatacenterList();
        this.setting = 0;
        this.form.setFieldsValue({
          type: 1,
        });
      });
    },
    handleChange(value) {
      if (value) {
        this.cloudType = value;
        this.$nextTick(() => {
          if (this.initObj && this.initObj.type === value) {
            this.form.setFieldsValue(this.initObj);
          }
        });
      }
    },
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          const postData = {
            datacenterId: values.datacenterId,
            type: values.type,
            name: values.name,
          };

          if (values.type === 1) {
            let clusterMigrationParam = {};
            clusterMigrationParam.restveleroIp = values.restveleroIp;
            if (this.setting > 0) {
              clusterMigrationParam.clusterName = values.clusterName;
            } else {
              clusterMigrationParam.clusterId = values.clusterId;
            }
            postData.clusterMigrationParam = clusterMigrationParam;
          } else if (values.type === 3) {
            postData.huaweiMigrationParam = {
              regionId: values.huaweiRegionId,
              accessKey: values.accessKey,
              secretKey: values.secretKey,
            };
          } else if (values.type === 2) {
            postData.aliMigrationParam = {
              regionId: values.aliRegionId,
              systemDiskSize: values.systemDiskSize,
              accessKeyId: values.accessKeyId,
              accessSecret: values.accessSecret,
            };
          }

          postAction("/cloud_resource/create", postData)
            .then((res) => {
              if (res.success) {
                this.$message.success("操作成功");
                if (this.cloudType === 1) {
                  this.$notification.open({
                    duration: 8,
                    message:
                      "在现有的受支持的Kubernetes集群上运行下面的kubectl命令，将其导入Rancher",
                    description: res.data,
                    style: {
                      width: "550px",
                      marginLeft: "-200px",
                      wordBreak: "break-all",
                    },
                  });
                }
                this.$emit("ok");
              }
            })
            .finally(() => {
              this.handleCancel();
            });
        }
      });
    },
    handleCancel() {
      this.visible = false;
      this.confirmLoading = false;
    },
  },
};
</script>
